<?php

/**
 * PhalApi_DB_MongoDB MongoDB存储
 *
 */
class PhalApi_DB_MongoDB /** implements PhalApi_DB */
{

    /**
     * @var array $_configs 数据库配置
     */
    protected $_configs = [];

    /**
     * @var boolean 是否开启调试模式，调试模式下会输出全部执行的SQL语句和对应消耗的时间
     */
    protected $debug = FALSE;

    /**
     * @var null  MongoDb Object
     */
    protected $_mongo = null;

    /**
     * @var  null  MongoCollection Object
     */
    protected $_collection = null;

    /**
     * @var string  dbName
     */
    protected $_dbName = '';

    /**
     * @var string  collectionName
     */
    protected $_collectionName = '';

    /**
     * @var  null MongoCursor Object
     */
    protected $_cursor = null;
    /**
     * @var array 条件
     */
    protected $comparison = ['neq' => 'ne', 'ne' => 'ne', 'gt' => 'gt', 'egt' => 'gte', 'gte' => 'gte', 'lt' => 'lt', 'elt' => 'lte', 'lte' => 'lte', 'in' => 'in', 'not in' => 'nin', 'nin' => 'nin'];


    /**
     * @param array $configs 数据库配置
     * @param boolean $debug 是否开启调试模式
     */
    public function __construct($configs, $debug = FALSE) {
        if ( !class_exists('mongoClient') ) {
            throw new PhalApi_Exception_InternalServerError(T("mongodb extension not found"));
        }
        $this->_configs = $configs;

        $this->debug = $debug;
    }
    /**
     * 连接数据库方法
     * @access public
     */
    public function connect($config='',$linkNum=0) {
        if ( !isset($this->linkID[$linkNum]) ) {
            if(empty($config))  $config =   $this->config;
            $host = 'mongodb://'.($config['username']?"{$config['username']}":'').($config['password']?":{$config['password']}@":'').$config['hostname'].($config['hostport']?":{$config['hostport']}":'').'/'.($config['database']?"{$config['database']}":'');
            try{
                $this->linkID[$linkNum] = new \mongoClient( $host,$this->config['params']);
            }catch (\MongoConnectionException $e){
                throw new PhalApi_Exception_InternalServerError(T("mongodb connect fail.".$e->getmessage()));
            }
        }
        return $this->linkID[$linkNum];
    }
    /**
     * 切换当前操作的Db和Collection
     * @access public
     * @param string $collection  collection
     * @param string $db  db
     * @param boolean $master 是否主服务器
     * @return void
     */
    public function switchCollection($collection,$db='',$master=true){
        // 当前没有连接 则首先进行数据库连接
        if ( !$this->_linkID ) $this->initConnect($master);
        try{
            if(!empty($db)) { // 传人Db则切换数据库
                // 当前MongoDb对象
                $this->_dbName  =  $db;
                $this->_mongo = $this->_linkID->selectDb($db);
            }
            // 当前MongoCollection对象
            if($this->debug) {
                $this->queryStr   =  $this->_dbName.'.getCollection('.$collection.')';
            }
            if($this->_collectionName != $collection) {
                $this->queryTimes++;
                N('db_query',1); // 兼容代码
                $this->debug(true);
                $this->_collection =  $this->_mongo->selectCollection($collection);
                $this->debug(false);
                $this->_collectionName  = $collection; // 记录当前Collection名称
            }
        }catch (MongoException $e){
            E($e->getMessage());
        }
    }
}
